
/**
 * @author Team 29
 * Contains the main method for the server app. Sets up a servergate,
 * servermessagehandler, loads calendar and user database, starts processing
 * inbound traffic.
 *
 */
public class Server {


	public static void main(String[] args) {
		Logger.log("STARTUP");
		ServerGate serv = new ServerGate();
		RecievedMessages messagequeue = new RecievedMessages();
		ServerMessageHandler servm = new ServerMessageHandler(serv, messagequeue);
		RecievedMessage currentmsg;
		String response;
		DatabaseUsers du = new DatabaseUsers();
		Database.clndr = Calendar.loadCalendar();
		Cryptography.init();
		
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run(){
				DatabaseUsers.saveUsers();
				Database.clndr.saveCalendar();
				System.out.println("The End...");
				Logger.log("SHUTDOWN");
			}
		});
		
		serv.smh = servm;
		Thread serverrunner = new Thread(servm);
		serverrunner.start();
		System.out.println("Starting...");
		while(true)
		{
			if(messagequeue.size>0)
			 {currentmsg = messagequeue.grab();	
			  response = Database.respondToRequest(currentmsg.message);
			  Logger.log("SENDING: " + response);
			  serv.send(response, currentmsg.source);
			  System.out.println("Sending "+ response);
			 }//end if
		}//end while
	}//end main

}//end class
